import axios from 'axios'
import Cookie from 'js-cookie'

class WinLogin {
  constructor ({ host, username, password, api }) {
    // this.host = host ? `http://${host}` : 'http://172.16.6.213'
    this.loginApi = api || '/base/api/v1/base/user/login'
    this.userInfoApi = '/base/api/v1/base/user/get_information'
    this.username = username
    this.password = password
    this.init()
  }
  async init () {
    // 当cookie中存在token 得不请求
    if (Cookie.getItem('Authorization')) {
      return
    }
    try {
      let accountRes = await axios.post(this.loginApi, {
        username: this.username,
        password: this.password
      })
      if (accountRes.data.success) {
        const token = accountRes.data.data.access_token
        let userInfoRes = await axios.post(this.userInfoApi, {
          token
        }, {
          headers: {
            Authorization: `Bearer ${token}`
          }
        })
        if (userInfoRes.data.success) {
          let sessionData = {
            Authorization: `Bearer ${token}`,
            'win-outpat': {
              account: accountRes.data.data,
              login: {
                doctorsInfo: userInfoRes.data.data
              }
            },
            userInfo: userInfoRes.data.data
          }
          let CookieData = {
            usersInfoId: userInfoRes.data.data.userId,
            userInfo: userInfoRes.data.data,
            Authorization: `Bearer ${token}`
          }
          Object.keys(sessionData).forEach(key => {
            window.sessionStorage.setItem(key, JSON.stringify(sessionData[key]))
          })
          Object.keys(CookieData).forEach(key => {
            Cookie.set(key, CookieData[key])
          })
        }
      }
    } catch (error) {
      console.error(error)
    }
  }
}

export default WinLogin
